package com.yuan.util.number;

import java.util.Random;

/**
 * Explain:     [随机数工具类]
 * Date:        [2017/9/25 14:08]
 * Coder:       [YouYuan]
 * Version:     [1.0]
 */
public class RandomUtil {

    /** 用于随机选的数字 */
    private static final String BASE_NUMBER = "0123456789";
    /** 用于随机选的字符 */
    private static final String BASE_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    /** 用于随机选的字符和数字 */
    private static final String BASE_CHAR_NUMBER = BASE_CHAR + BASE_NUMBER;

    public static final ThreadLocal<Random> RANDOM_LOCAL = new ThreadLocal<Random>(){
        @Override
        public Random initialValue() {
            return new Random();
        }
    };

    public static Random getLocalRandom(){
        return RANDOM_LOCAL.get();
    }

    public static int nextInt(){
        return getLocalRandom().nextInt();
    }

    public static int nextInt(int max){
        return getLocalRandom().nextInt(max);
    }

    /**
     * 获取指定区间的随机整数,在min（包括）和max（不包括）之间均匀分布的int值
     * @param min
     * @param max
     * @return
     */
    public static int nextInt(int min, int max){
        if (max < min) {
            throw new RuntimeException("max不能小于min");
        }
        if (min < 0) {
            throw new RuntimeException("区间不能小于min");
        }
        return getLocalRandom().nextInt(max - min) + min;
    }

    public static float nextFloat(){
        return getLocalRandom().nextFloat();
    }

    public static long nextLong(){
        return getLocalRandom().nextLong();
    }

    public static boolean nextBoolean(){
        return getLocalRandom().nextBoolean();
    }

    public static double nextDouble(){
        return getLocalRandom().nextDouble();
    }

    /**
     * 获得一个随机的字符串（只包含数字和字符）
     *
     * @param length 字符串的长度
     * @return 随机字符串
     */
    public static String randomString(int length) {
        return randomString(BASE_CHAR_NUMBER, length);
    }

    /**
     * 获得一个只包含数字的字符串
     *
     * @param length 字符串的长度
     * @return 随机字符串
     */
    public static String randomNumbers(int length) {
        return randomString(BASE_NUMBER, length);
    }

    /**
     * 获得一个随机的字符串
     *
     * @param baseString 随机字符选取的样本
     * @param length 字符串的长度
     * @return 随机字符串
     */
    public static String randomString(String baseString, int length) {
        final StringBuilder sb = new StringBuilder();
        if (length < 1) {
            length = 1;
        }
        int baseLength = baseString.length();
        for (int i = 0; i < length; i++) {
            int number = getLocalRandom().nextInt(baseLength);
            sb.append(baseString.charAt(number));
        }
        return sb.toString();
    }

}
